package com.ubing.gpermission.permission.processor;

import com.ubing.gpermission.permission.annotation.Permission;
import com.ubing.gpermission.permission.annotation.PermissionRouter;
import com.ubing.gpermission.permission.bean.PermissionSource;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;


import java.lang.reflect.Method;
import java.util.LinkedList;

public class PermissionBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		String[] beanNamesForAnnotation = beanFactory.getBeanNamesForAnnotation(PermissionRouter.class);
		PermissionSource permissionSource = new PermissionSource();
		for (String name : beanNamesForAnnotation) {
			try {
				Class<?> aClass = Class.forName(beanFactory.getBeanDefinition(name).getBeanClassName());
				PermissionRouter permissionRouter = aClass.getAnnotation(PermissionRouter.class);
				String routerValue = permissionRouter.value();

				permissionSource.getPermissionList().computeIfAbsent(routerValue, k -> new LinkedList<>());

				Method[] declaredMethods = aClass.getDeclaredMethods();
				for (Method declaredMethod : declaredMethods) {
					Permission annotation = declaredMethod.getAnnotation(Permission.class);
				if(annotation!=null) permissionSource.getPermissionList().get(routerValue).add(annotation.value());
				}
			} catch (ClassNotFoundException e) {
				throw new RuntimeException(e);
			}
		}
		beanFactory.registerSingleton("permissionSource",permissionSource);
	}
}
